package top.rish.minfire.config;

import freemarker.core.Environment;
import freemarker.template.*;
import org.noear.solon.Solon;
import org.noear.solon.boot.ServerProps;
import org.noear.solon.view.freemarker.FreemarkerRender;

import java.io.*;
import java.util.HashMap;
import java.util.UUID;

public class MyExceptionHandler implements TemplateExceptionHandler {

    private static final String PAGE_INLINE_ERROR_HTML = "/common/error/page-inline-error.html";
    @Override
    public void handleTemplateException(TemplateException te, Environment env, java.io.Writer out) throws TemplateException {
        try {
            Configuration provider = FreemarkerRender.global().getProvider();
            Configuration providerOfDebug = FreemarkerRender.global().getProviderOfDebug();
            Template template = null;
            if (providerOfDebug != null) {
                try {
                    template = providerOfDebug.getTemplate(PAGE_INLINE_ERROR_HTML, Solon.encoding());
                } catch (TemplateNotFoundException e) {
                    //忽略不计
                }
            }
            if (template == null) {
                template = provider.getTemplate(PAGE_INLINE_ERROR_HTML, Solon.encoding());
            }
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("error",te.toString());
            hashMap.put("errorId", UUID.randomUUID().toString());
            // 输出流
            template.process(hashMap, out);
            out.flush();
        } catch (IOException e) {
            throw new TemplateException("Error writing error message. Cause: " + e, env);
        }
    }
}